package com.ysucloud.api.service.impl;

import com.ysucloud.api.DTO.CartDTO;
import com.ysucloud.api.DTO.OrderDTO;
import com.ysucloud.api.dataobject.OrderDetail;
import com.ysucloud.api.dataobject.OrderMaster;
import com.ysucloud.api.dataobject.ProductInfo;
import com.ysucloud.api.enums.OrderStatusEnum;
import com.ysucloud.api.enums.PayStatusEnum;
import com.ysucloud.api.enums.ResultEnum;
import com.ysucloud.api.exception.OrderException;
import com.ysucloud.api.repository.OrderDetailRepository;
import com.ysucloud.api.repository.OrderMasterRepository;
import com.ysucloud.api.service.OrderService;
import com.ysucloud.api.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description: api
 * Created by aininot260 on 2019/6/27 21:31
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    /**
     * 开启自动事务 防止减库存造成的错误
     */
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        //将所有商品ID变为列表
        List<Integer> productIdList = orderDTO.getOrderDetailList().stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());

        //查询
        List<ProductInfo> productInfoList = productService.findList(productIdList);

        //计算总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        OrderMaster orderMaster=new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);

        //此处总价未知，置0
        orderMaster.setOrderAmount(orderAmount);

        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster = orderMasterRepository.save(orderMaster);

        for(OrderDetail orderDetail:  orderDTO.getOrderDetailList())
        {
            for(ProductInfo productInfo: productInfoList)
            {
                if(productInfo.getProductId()==orderDetail.getProductId())
                {
                    orderAmount = productInfo.getProductPrice()
                            .multiply(new BigDecimal(orderDetail.getProductQuantity()))//乘法
                            .add(orderAmount);//加法
                    //拷贝，但是注意要清楚创建时间和修改时间
                    BeanUtils.copyProperties(productInfo,orderDetail);
                    orderDetail.setOrderId(orderMaster.getOrderId());
                    orderDetail.setCreateTime(null);
                    orderDetail.setUpdateTime(null);
                    //订单详情入库
                    orderDetailRepository.save(orderDetail);
                }
            }
        }
        orderMaster.setOrderAmount(orderAmount);
        orderMasterRepository.save(orderMaster);

        List<CartDTO> cartDTOList=orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.decreaseStock(cartDTOList);//减库存
        orderDTO.setOrderId(orderMaster.getOrderId());

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(Integer orderId) {
        OrderDTO orderDTO=new OrderDTO();
        orderDTO.setOrderDetailList(orderDetailRepository.findByOrderId(orderId));
        return orderDTO;
    }

    @Override
    public List<OrderDTO> findList(Integer buyerId) {
        List<OrderMaster> orderMasterList=orderMasterRepository.findByBuyerId(buyerId);
        List<OrderDTO> orderDTOList=new ArrayList<> ();
        for(OrderMaster orderMaster: orderMasterList)
        {
            OrderDTO orderDTO=new OrderDTO();
            BeanUtils.copyProperties(orderMaster,orderDTO);
            orderDTOList.add(orderDTO);
        }
        return orderDTOList;
    }



    /** 取消订单（重新实现） */
    /*@Override
    public void cancel(Integer orderId) {
        Optional<OrderMaster> productInfoOptional=orderMasterRepository.findById(orderId);
        OrderMaster orderMaster=productInfoOptional.get();
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        orderMasterRepository.save(orderMaster);
    }*/
    @Override
    public void cancel(Integer orderId, Integer buyerId) {
        OrderMaster orderMaster =
                orderMasterRepository.findByBuyerIdAndOrderId(buyerId,orderId);
        if(orderMaster == null){
            throw new OrderException(ResultEnum.MAPPING_ERROR.getCode(),
                    ResultEnum.MAPPING_ERROR.getMessage());
        }

        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        orderMaster.setUpdateTime(null);

        orderMasterRepository.save(orderMaster);
    }


    @Override
    public OrderDTO findDetail(Integer orderId,Integer buyerId) {
        //查询主记录
        OrderMaster orderMaster =
                orderMasterRepository.findByBuyerIdAndOrderId(buyerId,orderId);

        //主记录查询为空
        if(orderMaster == null){
            throw new OrderException(ResultEnum.MAPPING_ERROR.getCode(),
                    ResultEnum.MAPPING_ERROR.getMessage());
        }

        OrderDTO result = new OrderDTO();

        BeanUtils.copyProperties(orderMaster,result);

        List<OrderDetail> orderDetails = orderDetailRepository.findByOrderId(orderId);

        result.setOrderDetailList(orderDetails);

        return result;
    }

}
